package com.xywy.common.net;

import org.apache.http.NameValuePair;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 每次都去new一个task可能有些问题，需要重新考虑
 * new task的时候可以覆写几个回调方法如onErr()
 *
 * @author xgd
 */
public class NetWorkTask {

    protected List<NameValuePair> nameValuePair;
    protected static final String TAG = "AsynTask";


    private NetWorkTask() {
    }

    /**
     * 静态单例
     */
    public static NetWorkTask getInstance() {
        return singletonHolder.instance;
    }

    private static class singletonHolder {
        private static NetWorkTask instance = new NetWorkTask();
    }


    /**
     * 执行网络请求
     *
     * @param parser params,封装了参数的请求
     */
    public Parser client(Parser parser) {

        nameValuePair = parser.nameValuePair;
        // 根据request判断请求类型
        if (nameValuePair == null) {
            // 执行POST
            if (parser.request.equalsIgnoreCase("post")) {
                parser = NetUtil.post(parser);

            }

            //执行GET
            else if (parser.request.equalsIgnoreCase("get")) {
                parser = NetUtil.get(parser);
            }

            //执行上传
            else if (parser.request.equalsIgnoreCase("upload")) {
                //上传
                parser = NetUtil.upload(parser);

                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                Date curDate = new Date(System.currentTimeMillis());//获取当前时间
                String str = formatter.format(curDate);
                //获取参数
                Long tid = (long) 0;
                Object tmpTid = parser.map.get("tid");
                if (tmpTid instanceof Long) {
                    tid = (Long) tmpTid;
                } else if (tmpTid instanceof String && !tmpTid.equals("")) {
                    tid = Long.parseLong(tmpTid.toString());
                }
                JSONObject object = parser.retBackJson();  //服务端返回数据
                //继续执行后续流程
                if (tid != null && tid != 0 && object != null) {

                }
            }
        } else {
            if (parser.request.equalsIgnoreCase("post")) {
                parser = NetUtil.post(nameValuePair, parser);
            } else if (parser.request.equalsIgnoreCase("get")) {
                parser = NetUtil.get(parser);
            } else if (parser.request.equalsIgnoreCase("upload")) {
                parser = NetUtil.upload(parser);
            }
        }

        //对象：各种响应码&Json字符串。
        return parser;
    }

}
